package com.service.business.utils;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.DefaultResult;
import cn.jpush.api.JPushClient;
import cn.jpush.api.device.TagListResult;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.service.core.exception.CommonException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import cn.jpush.api.push.model.PushPayload;

import java.util.HashSet;

public class JPushUtils {


//    @Value("${JPUSH_MASTER_SECRET}")
//    private static String JPUSH_MASTER_SECRET;
//
//    @Value("${JPUSH_APP_KEY}")
//    private static String JPUSH_APP_KEY;

    private static JPushClient jpushClient = new JPushClient("0f25dea8b6bf338e5e7518e4", "e37e0b5d0e8bdbfd814ec72c", null, ClientConfig.getInstance());

    /**
     * 给某设备发推送消息
     * @param phoneId
     * @param alert
     * @param title
     * @return
     * @throws Exception
     */
    public static void sendOneMsg(String phoneId,String alert,String title){
        commonSend(phoneId,alert,title);
    }


    public static void registerTag(String phoneId){
        phoneId = phoneId.replaceAll("-","");
        HashSet<String> tagSet = new HashSet<String>();
        tagSet.add(phoneId);
        try {
            TagListResult lst = jpushClient.getTagList();
            DefaultResult result = jpushClient.updateDeviceTagAlias("", null, tagSet, null);
        } catch (APIConnectionException | APIRequestException e) {
            throw new CommonException(e.getMessage());
        }
    }



    private static void commonSend(String phoneId, String alert, String title){
        PushPayload payload = buildPushObject_tagAnd_alertWithExtrasAndMessage(phoneId,alert,title);

        try{
            jpushClient.sendPush(payload);
//            ("Got result - " + result);
        } catch (APIConnectionException | APIRequestException e) {
            throw new CommonException(e.getMessage());
            // Connection error, should retry later
//            LOG.error("Connection error, should retry later", e);
        } // Should review the error, and fix the request
        //            LOG.error("Should review the error, and fix the request", e);
        //            LOG.info("HTTP Status: " + e.getStatus());
        //            LOG.info("Error Code: " + e.getErrorCode());
        //            LOG.info("Error Message: " + e.getErrorMessage());

    }


    private static PushPayload buildPushObject_tagAnd_alertWithExtrasAndMessage(String tag,String alert,String title){
        String platform = getPlatformStringFromPhoneId(tag);
        return PushPayload.newBuilder()
                .setPlatform(buildPlatform(platform))
                .setAudience(Audience.tag(tag))
                .setNotification(buidNotification(platform,alert,title))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)
                        .build())
                .build();
    }


    /**
     * 从PHONEID中获取平台信息
     * 79B9B79C-E16D-49FE-8F0F-8AC41D08C5A4 iphone
     * 868895035675655 ANDROID
     * @return
     */
    private static String getPlatformStringFromPhoneId(String phoneId){
        if(StringUtils.isEmpty(phoneId)){
            throw new CommonException("Phone Id Cannot be Null");
        }
        phoneId = phoneId.replaceAll("-","");//去除iphone里的 -
        boolean isIOS = phoneId.matches(".*[a-zA-Z]+.*");//【含有英文】true
        if(isIOS){
            return "IOS";
        }else{
            return "ANDROID";
        }
    }

    /**
     * 构建平台
     * @param platform
     * @return
     */
    private static Platform buildPlatform(String platform){
        if(platform.equals("IOS")){
            return Platform.ios();
        }else if(platform.equals("ANDROID")){
            return Platform.android();
        }else{
            return Platform.all();
        }
    }

    /**
     * 构建平台消息
     * @param platform
     * @param alert
     * @param title
     * @return
     */
    private static Notification buidNotification(String platform, String alert, String title){
        if(platform.equals("IOS")){
            return Notification.newBuilder()
                    .addPlatformNotification(IosNotification.newBuilder()
                            .setAlert(alert)
                            .setBadge(1)
                            .setSound("happy")
                            .addExtra("type", 2)//打开应用
                            .build())
                    .build();
        }else if(platform.equals("ANDROID")){
            return Notification.android(alert, title, null);
        }else{
            return Notification.alert(alert);
        }
    }
}
